package com.android.namecard.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;

import com.android.namecard.R;
import com.android.namecard.entity.Namecard;
import com.android.namecard.model.NamecardDBHelper;

public class NamecardListActivity extends TabActivity implements OnGestureListener{
	//声明TabHost对象
	private TabHost mTabHost;
	private AutoCompleteTextView searchView ;
	private List<Map<String, Object>> dataForList = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> dataForSearch = new ArrayList<Map<String, Object>>();
	private ArrayList nameForList = null;
	private ArrayList nameForSearch = null;
	private ListView listView = null;
	ProgressDialog m_Dialog;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.namecard_list);
		mTabHost = getTabHost();
		/* 为TabHost添加标签 */
		//新建一个newTabSpec(newTabSpec)
		//设置其标签和图标(setIndicator)
		//设置内容(setContent)
		mTabHost.addTab(mTabHost.newTabSpec("tab_private")
	    		.setIndicator("私人名片",getResources().getDrawable(R.drawable.img1))
	    		.setContent(R.id.private_list));
	    mTabHost.addTab(mTabHost.newTabSpec("tab_commercial")
	    		.setIndicator("商用名片",getResources().getDrawable(R.drawable.img2))
	    		.setContent(R.id.commercial_list));
	    mTabHost.addTab(mTabHost.newTabSpec("tab_public")
	    		.setIndicator("公共名片",getResources().getDrawable(R.drawable.img3))
	    		.setContent(R.id.public_list));
		
        m_Dialog = ProgressDialog.show(
    			NamecardListActivity.this, 
    			"请等待", 
    			"正在为您载入数据...",
    			true);
		
		
        new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
		        //取得名片id
				prepareDataForName();
				prepareDataForList("private");
				try{
					sleep(500);
				}catch(Exception e){}
	            handler.post(runnable);
			}
        }.start();
	}
	
	/**
	 * 私人名片函数
	 */
	private void privateList(){
        listView = (ListView)findViewById(R.id.private_list);
		SimpleAdapter adapter = new SimpleAdapter(this, dataForList,
				R.layout.list_item, 
				new String[] {"image", "name", "namecardId", "company", "career" },
				new int[] {
				R.id.type_img, R.id.mname, R.id.mnamecard_id, R.id.mcompany, R.id.mcareer });
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(listener);
	}
	
	/**
	 * 商业名片函数
	 */
	private void commercialList(){
        listView = (ListView)findViewById(R.id.commercial_list);
		SimpleAdapter adapter = new SimpleAdapter(this, dataForList,
				R.layout.list_item, 
				new String[] {"image", "name", "namecardId", "company", "career" },
				new int[] {
				R.id.type_img, R.id.mname, R.id.mnamecard_id, R.id.mcompany, R.id.mcareer });
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(listener);
	}
	
	/**
	 * 公用名片函数
	 */
	private void publicList(){
        listView = (ListView)findViewById(R.id.public_list);
		SimpleAdapter adapter = new SimpleAdapter(this, dataForList,
				R.layout.list_item, 
				new String[] {"image", "name", "namecardId", "company", "career" },
				new int[] {
				R.id.type_img, R.id.mname, R.id.mnamecard_id, R.id.mcompany, R.id.mcareer });
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(listener);
	}
	
	/**
	 * 从数据库查询信息
	 * @param type  按名片类型查
	 * @param context
	 */
	private void prepareDataForList(String type) {
		//从数据库取出数据
		NamecardDBHelper namecardDB = new NamecardDBHelper(getBaseContext());
	    nameForList = namecardDB.getNamecardListByType(type);
		Log.i("size", String.valueOf(nameForList.size()));
		dataForList = new ArrayList<Map<String, Object>>();
		Map<String, Object> item;
		if(nameForList.size()>0){
			for(int i = 0; i < nameForList.size(); i++){
				item = new HashMap<String, Object>();
				Namecard namecard = (Namecard)nameForList.get(i);
				if(namecard.getType().equals(NamecardDBHelper.PRIVATE_TYPE)){
					item.put("image", R.drawable.img1);
				}else if(namecard.getType().equals(NamecardDBHelper.COMMERCIAL_TYPE)){
					item.put("image", R.drawable.img2);
				}else{
					item.put("image", R.drawable.img3);
				}
				item.put("name", namecard.getName());
				item.put("namecardId", namecard.getNamecardId());
				item.put("company", namecard.getCompany());
				item.put("career", namecard.getCareer());
				dataForList.add(item);
			}
		}else{
			
		}
		namecardDB.close();
	}
	
	/**
	 * 为搜索框准备数据
	 * @param context
	 */
	private void prepareDataForName(){
		//从数据库取出数据
		NamecardDBHelper namecardDB = new NamecardDBHelper(getBaseContext());
	    nameForSearch = namecardDB.getNamecardListByType("all");
	    dataForSearch = new ArrayList<Map<String, Object>>();
		Map<String, Object> item;
		if(nameForSearch.size()>0){
			for(int i = 0; i < nameForSearch.size(); i++){
				item = new HashMap<String, Object>();
				Namecard namecard = (Namecard)nameForSearch.get(i);
				if(namecard.getType().equals(NamecardDBHelper.PRIVATE_TYPE)){
					item.put("image", R.drawable.img1);
				}else if(namecard.getType().equals(NamecardDBHelper.COMMERCIAL_TYPE)){
					item.put("image", R.drawable.img2);
				}else{
					item.put("image", R.drawable.img3);
				}
				item.put("name", namecard.getName());
				item.put("namecardId", namecard.getNamecardId());
				item.put("company", namecard.getCompany());
				item.put("career", namecard.getCareer());
				dataForSearch.add(item);
			}
		}else{
			
		}
	}
	
	
	
	/**
	 * 进入名片
	 * @param namecardId
	 */
	private void intoTheNamecard(String namecardId){
		Intent intent = new Intent(NamecardListActivity.this, NamecardActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("namecardId", namecardId);
		intent.putExtras(bundle);
		startActivityForResult(intent,0);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return new GestureDetector(this).onTouchEvent(event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch(resultCode){
		case 0:
			//刷新列表
			this.prepareDataForName();
			int index = mTabHost.getCurrentTab();
			if(index==0){
				prepareDataForList("private");
				privateList();
			}else if(index==1){
				prepareDataForList("commercial");
				commercialList();
			}else{
				prepareDataForList("public");
				publicList();
			}
			break;
		}
	}
	
	private void updateUI(){
		searchView = (AutoCompleteTextView)findViewById(R.id.auto_search_view);
		searchView.setThreshold(0);
		
		SimpleAdapter adapter = new SimpleAdapter(this, dataForSearch,
				R.layout.result_item, 
				new String[] {"name", "namecardId", "company", "career" },
				new int[] {
				R.id.mname, R.id.mnamecard_id, R.id.mcompany, R.id.mcareer });
		searchView.setAdapter(adapter);
		searchView.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String selectText = String.valueOf(searchView.getText());
				int start = selectText.lastIndexOf("namecardId=")+11;
				String namecardId = selectText.substring(start, start+13);
				Log.i("id===============",selectText.substring(start, start+13));
				searchView.setText(null);
				intoTheNamecard(namecardId);
			}
		});
		
		//设置第一次进入的privateList
		privateList();
		
	    //设置TabHost的背景颜色
	    //mTabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));
	    //设置TabHost的背景图片资源
	    //mTabHost.setBackgroundResource(R.drawable.bg0);
	    
	    //设置当前显示哪一个标签
	    mTabHost.setCurrentTab(0);
	    //标签切换事件处理，setOnTabChangedListener 
	    mTabHost.setOnTabChangedListener(new OnTabChangeListener(){
	    	// TODO Auto-generated method stub
            @Override
            public void onTabChanged(String tabId){
            	if(tabId.equals("tab_private")){
            		prepareDataForList("private");
            		privateList();
            	}else if(tabId.equals("tab_commercial")){
            		prepareDataForList("commercial");
            		commercialList();
            	}else if(tabId.equals("tab_public")){
            		prepareDataForList("public");
            		publicList();
            	}
                
            }
        });
	    
	}
	
    final Handler handler = new Handler();
    
	final Runnable runnable = new Runnable(){
		@Override
		public void run() {
			// TODO Auto-generated method stub
			updateUI();
			m_Dialog.dismiss();
		}
	};
	
	OnItemClickListener listener = new OnItemClickListener(){
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int index,
				long arg3) {
			// TODO Auto-generated method stub
			Namecard namecard = (Namecard)nameForList.get(index);
			intoTheNamecard(namecard.getNamecardId());
		}
    };
}
